/**
 * 
 */
package com.gr.staffpm.feedback.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.gr.staffpm.dao.HibernateDao;
import com.gr.staffpm.datatypes.Feedback;
import com.gr.staffpm.datatypes.User;


/**
 * @author Graham Rhodes 3 Mar 2011 12:21:03
 */
@Transactional
@SuppressWarnings("unchecked")
@Repository("feedbackDAO")
public class HibernateFeedbackDAO extends HibernateDao implements FeedbackDAO {

    private static final long serialVersionUID = 1L;

    @Override
    public void addOrUpdateFeedback(Feedback feedback) {
        getSession().saveOrUpdate(feedback);
    }

    @Override
    public List<Feedback> getFeedbackForUserBetweenDates(User user, Date start, Date end) {
        Criteria crit = getSession().createCriteria(Feedback.class);
        crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        crit.add(Restrictions.eq(Feedback.RECEIVER, user));
        crit.add(Restrictions.between(Feedback.CREATED, start, end));
        List<Feedback> result = crit.list();
        //getSession().disconnect();
        return result;
    }

    @Override
    public List<Feedback> getFeedbackForUserBetweenDatesWithRating(User user, DateTime start, DateTime end, int rating) {
        Criteria crit = getSession().createCriteria(Feedback.class);
        crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        crit.add(Restrictions.eq(Feedback.RECEIVER, user));
        crit.add(Restrictions.between(Feedback.CREATED, start.toDate(), end.toDate()));
        crit.add(Restrictions.eq(Feedback.RATING, rating));
        List<Feedback> result = crit.list();
        //getSession().disconnect();
        return result;
    }

    @Override
    public int countRatingBetween(User user, DateTime start, DateTime end, int rating) {
        Criteria crit = getSession().createCriteria(Feedback.class);
        crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        crit.add(Restrictions.eq(Feedback.RECEIVER, user));
        crit.add(Restrictions.between(Feedback.CREATED, start.toDate(), end.toDate()));
        crit.add(Restrictions.eq(Feedback.RATING, rating));
        crit.setProjection(Projections.rowCount());
        int result = ((Long) crit.uniqueResult()).intValue();
        //getSession().disconnect();
        return result;
    }

}
